package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.account.service.WalletService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.utils.RandomUtils;
import com.ruitaowang.core.utils.TimeUtils;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.*;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by neal on 1/3/17.
 */
@RestController
public class APILocalOrderController extends BaseController {

    @Autowired
    private LocalOrderService localOrdersService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private CompanyProductService companyProductService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private UserProfitService userProfitService;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private CouponService couponService;

    @RequestMapping("/api/localorders")
    public String list() {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company company =new Company();
        company.setUserId(user.getId());
        List<Company> companyList = companyService.select(company);

        if(ObjectUtils.isEmpty(companyList)){
            return this.renderJson(MsgOut.error("您还不是商家用户"));
        }else{
            company = companyList.get(0);
        }

        List<LocalOrder> list;
        LocalOrder localOrders = new LocalOrder();
        localOrders.setCompanyId(company.getCompanyId());
        list = localOrdersService.select(localOrders);
        if(!ObjectUtils.isEmpty(list)){
            for(LocalOrder localOrder : list){
                localOrder.setRemark(sysUserService.selectByPK(localOrder.getUserId()).getNickname());
            }
        }
        MsgOut o = MsgOut.success(list);
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/admin/localOrders 后台管理-订单管理-扫码订单列表
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/localOrders
     *
     * @apiName findLocalOrdersPage
     * @apiGroup LocalOrder
     *
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "auditStatus": 0,
     *                   "auditUserId": 0,
     *                   "companyId": 1,
     *                   "ctime": 1503384993775,
     *                   "discountId": 0,
     *                   "mtime": 1503385002341,
     *                   "orderId": 24,
     *                   "orderSn": "20170822145633775l1",
     *                   "payStatus": 1,
     *                   "price": 700,
     *                   "productId": 147,
     *                   "remark": "马英乘Neal",
     *                   "rstatus": 0,
     *                   "score": 0,
     *                   "userId": 1
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "title":"成功",
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/localOrders"
     *  }
     */
    @RequestMapping("/api/admin/localOrders")
    public String findLocalOrderPage(LocalOrder localOrder,int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        localOrder.setPage(page);
        List<LocalOrderVO> localOrderVOS = new ArrayList<>();
        List<LocalOrder> localOrders=localOrdersService.selectForPage(localOrder);
        for (LocalOrder lo:localOrders){
            LocalOrderVO localOrderVO = new LocalOrderVO();
            BeanUtils.copyProperties(lo, localOrderVO);
            localOrderVO.setStrnickname(sysUserService.selectByPK(lo.getUserId()).getNickname());
            localOrderVO.setStrcompanyname(companyService.selectByPK(lo.getCompanyId()).getCompanyName());
            localOrderVOS.add(localOrderVO);
        }
        MsgOut o = MsgOut.success(localOrderVOS);
        o.setRecords(localOrder.getRecords());
        o.setTotal(localOrder.getTotal());
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/localOrder/fjOrder")
    public String fjOrder(LocalOrder localOrder,int page){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        localOrder.setPage(page);
        List<LocalOrder> localOrderList = localOrdersService.fjOrder(localOrder);
        MsgOut o = MsgOut.success(localOrderList);
        o.setRecords(localOrder.getRecords());
        o.setTotal(localOrder.getTotal());
        return this.renderJson(o);
    }

    /**
     * 查询扫码订单
     * @param localOrder
     * @return
     */
    @RequestMapping("/api/wap/localOrders")
    public String localOrders(LocalOrder localOrder) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(localOrder)) {
            return this.renderJson(MsgOut.error("参数错误"));
        }
        LocalOrder order=localOrdersService.selectByPK(localOrder.getOrderId());
        MsgOut o = MsgOut.success(order);
        return this.renderJson(o);
    }
    @RequestMapping("/api/wap/user/localOrders")
    public String wapUserLocalOrderPage(LocalOrder localOrder,int page,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser user = sysUserService.selectByPK(Long.parseLong(userId));
        List listOut=new ArrayList();
        localOrder.setPage(page);
        localOrder.setUserId(user.getId());
        List<LocalOrder> localOrders=localOrdersService.selectForPage(localOrder);
        for (LocalOrder lo:localOrders){
            HashMap map=new HashMap();
            map.put("order",lo);

            Company company=companyService.selectByPK(lo.getCompanyId());
            if (!ObjectUtils.isEmpty(company)){
                map.put("company",company);
            }
            listOut.add(map);
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(localOrder.getRecords());
        o.setTotal(localOrder.getTotal());
        return this.renderJson(o);
    }
    @RequestMapping("/api/wap/company/localOrders")
    public String wapCompanyLocalOrderPage(LocalOrder localOrder,int page,@RequestHeader(value="headId",required = false) Long userId) {
        //SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List listOut=new ArrayList();
        localOrder.setPage(page);
        Company company=companyService.selectByUserId(userId);
        if (ObjectUtils.isEmpty(company)){
            return this.renderJson(MsgOut.error("no data."));
        }
        localOrder.setCompanyId(company.getCompanyId());
        List<LocalOrder> localOrders=localOrdersService.selectForPage(localOrder);
        for (LocalOrder lo:localOrders){
            HashMap map=new HashMap();
            map.put("order",lo);

            SysUser sysUser=sysUserService.selectByPK(lo.getUserId());
            if (!ObjectUtils.isEmpty(sysUser)){
                map.put("sysUser",sysUser);
            }
            listOut.add(map);
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(localOrder.getRecords());
        o.setTotal(localOrder.getTotal());
        return this.renderJson(o);
    }

    /**
     * @api {post} /api/admin/localOrder/cellEdit 后台管理-订单-更新订单信息-[审核状态]
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/localOrder/cellEdit
     * @apiPermission admin
     *
     * @apiName updateLocalOrderForCellEdit
     * @apiGroup LocalOrder
     *
     * @apiParam {int} id 订单ID[必选].
     * @apiParam {int} auditStatus 审核状态[必选].
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                    "auditStatus": 2,
     *                    "id": 363,
     *                    "oper":edit
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "title":"成功",
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/order/cellEdit"
     *  }
     */
    @RequestMapping(value = "/api/admin/localOrder/cellEdit", method = RequestMethod.POST)
    public String updateLocalOrderForCellEdit(LocalOrder localOrder, Long id){
        localOrder.setOrderId(id);
        localOrdersService.update(localOrder);
        MsgOut o = MsgOut.success(localOrder);
        return this.renderJson(o);
    }
    //地面店订单
    @RequestMapping("/api/localorders/company")
    public String list4company(int rows, int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company company =new Company();
        company.setUserId(user.getId());
        List<Company> companyList = companyService.select(company);
        if(ObjectUtils.isEmpty(companyList)){
            return this.renderJson(MsgOut.error("您还不是商家用户"));
        }
        company = companyList.get(0);
        LocalOrder localOrders = new LocalOrder();
        localOrders.setCompanyId(company.getCompanyId());
        localOrders.setPage(page);
        localOrders.setRows(rows);
        List<LocalOrder> list = localOrdersService.selectForPage(localOrders);
        UserProfitVO userProfitVO = null;
        SysUser user1 = null;
        List<UserProfitVO> userProfitVOs = new ArrayList<>();
        if(!ObjectUtils.isEmpty(list)){
            for(LocalOrder up : list){
                userProfitVO = new UserProfitVO();
                user1 = sysUserService.selectByPK(up.getUserId());
                if(!ObjectUtils.isEmpty(user1)){
                    userProfitVO.setNickname(user1.getNickname());
                    userProfitVO.setHeadimgurl(user1.getHeadimgurl());
                }
                userProfitVO.setAmount(up.getPrice());
                userProfitVO.setCtime(up.getCtime());
                userProfitVO.setUserProfit((up.getPrice() - up.getScore() * 100 / 2) );
                userProfitVOs.add(userProfitVO);
            }
        }
        MsgOut o = MsgOut.success(userProfitVOs);

        o.setRecords(localOrders.getRecords());
        o.setTotal(localOrders.getTotal());
        return this.renderJson(o);
    }

    /**
     * 扫码支付订单
     * @param price
     * @param fk
     * @param id
     * @param score
     * @param type
     * @return
     */
    @RequestMapping(value = "/api/wap/localorders", method = RequestMethod.POST)
    public String create(Integer price, String fk,Long id,Integer score,byte type,Integer amount,String remark) {
        SysUser user = LYSecurityUtil.currentSysUser();
        String[] iDs = fk.split("-");
        if (ObjectUtils.isEmpty(user)) {
//            return this.renderJson(MsgOut.error("Plz login."));
            MsgOut o=MsgOut.error("登录失败!");
            o.setCode(6);
            return this.renderJson(o);
//            user.setId(Long.valueOf(iDs[2]));
        }
        if(ObjectUtils.isEmpty(fk)){
            return this.renderJson(MsgOut.error());
        }
        if(ObjectUtils.isEmpty(iDs) || iDs.length < 4){
            return this.renderJson(MsgOut.error());
        }
//        Company company = new Company();
//        company.setUserId(Long.valueOf(iDs[3]));
        Company c = companyService.selectByPK(Long.valueOf(iDs[3]));
        if (ObjectUtils.isEmpty(c)) {
            return this.renderJson(MsgOut.error("该商户信息错误"));
        }
        if (user.getId().equals(c. getUserId())){
            MsgOut o=MsgOut.error("自己不可购买自己店铺商品哦!");
            o.setCode(6);
            return this.renderJson(o);
        }
        //检测参数是否正确
        if (!ObjectUtils.isEmpty(amount)){
            if (type == 1){
                if (ObjectUtils.isEmpty(price)){
                    return this.renderJson(MsgOut.error("参数错误{price}"));
                }
            }else if (type==2){
                if (ObjectUtils.isEmpty(score)){
                    return this.renderJson(MsgOut.error("参数错误{score}"));
                }
            }else if (type == 3){
                if (ObjectUtils.isEmpty(score) || ObjectUtils.isEmpty(price)){
                    return this.renderJson(MsgOut.error("参数错误{score}{price}"));
                }
            }else if (type == 4){
                if (ObjectUtils.isEmpty(score) || ObjectUtils.isEmpty(price) || ObjectUtils.isEmpty(id)){
                    return this.renderJson(MsgOut.error("参数错误{score}{price}{id}"));
                }
            }else if (type == 5){
                if (ObjectUtils.isEmpty(price) || ObjectUtils.isEmpty(id)){
                    return this.renderJson(MsgOut.error("参数错误{price}{id}"));
                }
            }else if (type == 6){
                if (ObjectUtils.isEmpty(score) || ObjectUtils.isEmpty(id)){
                    return this.renderJson(MsgOut.error("参数错误{score}{id}"));
                }
            }
            Coupon coupon=couponService.selectByPK(id);
            if(!ObjectUtils.isEmpty(coupon)){
                if (amount - price - score - (coupon.getScore1()*100) != 0 ){
                    return this.renderJson(MsgOut.error("参数错误{amount}"));
                }
            }else {
                if (amount - price - score != 0 ){
                    return this.renderJson(MsgOut.error("参数错误{no coupon}"));
                }
            }

        }else {
            return this.renderJson(MsgOut.error("参数错误{amount null}"));
        }

        LocalOrder localOrders = new LocalOrder();
        localOrders.setPrice(price);
        localOrders.setLocalOrderType(type);
        localOrders.setUserId(user.getId());
        localOrders.setCompanyId(c.getCompanyId());
        localOrders.setOrderSn(RandomUtils.genOrderSN(user.getId()));
        localOrders.setProductId(Long.valueOf(iDs[3]));
        localOrders.setAmount(amount);
        localOrders.setRemark(remark);

        //检测积分
        if(type!=1&&type!=5){
            if(!ObjectUtils.isEmpty(score) || score != 0){
                Wallet wallet=walletService.selectByPK(user.getId());
                if(ObjectUtils.isEmpty(wallet)){
                    wallet = new Wallet();
                    wallet.setUserId(user.getId());
                    walletService.insert(wallet);
                }
                if (wallet.getUserScore() >= score){
                    localOrders.setScore(score);
                }else {
                    return this.renderJson(MsgOut.error("该用户所持积分不满足扣除积分金额"));
                }
            }        	
        }

        //检测优惠券
        if(type>3){
            if (!ObjectUtils.isEmpty(id) || id != 0){
                Coupon coupon=couponService.selectByPK(id);
                if (!ObjectUtils.isEmpty(coupon) && coupon.getCouponType() ==0){
                    //满减钱数添加进扫码订单
                    localOrders.setFavorablePrice(coupon.getScore1()*100);
                    //优惠券ID
                    localOrders.setDiscountId(id);
                }
            }        	
        }
        localOrdersService.insert(localOrders);
        MsgOut o = MsgOut.success(localOrders);
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/localorders/jmpay", method = RequestMethod.POST)
    public String create(Integer price) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }

        LocalOrder localOrders = new LocalOrder();
        localOrders.setPrice(price);
        localOrders.setUserId(user.getId());
        localOrders.setCompanyId(1l);
        localOrders.setOrderSn(RandomUtils.genOrderSN(user.getId()));
        localOrders.setProductId(1l);
        localOrdersService.insert(localOrders);

        MsgOut o = MsgOut.success(localOrders);
        return this.renderJson(o);
    }

    /**
     * @api {put} /api/admin/localOrders 后台管理-扫码订单-批量更新订单信息
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/localOrders
     * @apiPermission admin
     *
     * @apiName updateLocalOrder
     * @apiGroup LocalOrder
     *
     * @apiParam {int} orderId 订单ID[必选].
     * @apiParam {int} auditStatus 审核状态[必选].
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                    "auditStatus": 2,
     *                    "orderId": 363,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "title":"成功",
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/localOrders"
     *  }
     */

    @RequestMapping(value = "/api/admin/localOrders", method = RequestMethod.PUT)
    public String updateLocalOrder(LocalOrder localOrders) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        localOrdersService.update(localOrders);
        MsgOut o = MsgOut.success(localOrders);
        return this.renderJson(o);
    }

    /**
     * @api {delete} /api/admin/localOrders/{orderId} 后台管理-订单管理--扫码订单--删除订单
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/localOrders/{orderId}
     * @apiPermission admin
     *
     * @apiName deleteLocalOrder
     * @apiGroup LocalOrder
     *
     * @apiParam {long} orderId 订单ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":1,
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/localOrders/{orderId}"
     *  }
     */
    @RequestMapping(value = "/api/admin/localOrders/{orderId}", method = RequestMethod.DELETE)
    public String deleteLocalOrder(@PathVariable Long orderId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(localOrdersService.delete(orderId));
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/localorders/{orderId}", method = RequestMethod.DELETE)
    public String delete(@PathVariable Long orderId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(localOrdersService.delete(orderId));
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/localorders/{orderId}")
    public String get(@PathVariable Long orderId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(localOrdersService.selectByPK(orderId));
        return this.renderJson(o);
    }


    /**
     * @api {get} /api/admin/localOrders/excel/{orderId} 后台管理-订单管理-商城订单-Excel导出
     * @apiSampleRequest /api/admin/localOrders/excel/{orderId}
     * @apiVersion 0.1.0
     * @apiName adminLocalOrderExcel
     * @apiGroup LocalOrder
     *
     * @apiParam {long} orderId 订单ID.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     * @apiError Internal Server Error.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/localOrders/excel/{orderId}"
     *  }
     */

    @RequestMapping(value = {"/api/admin/localOrders/excel/{orderId}"})
    public void adminLocalOrderExcel(@PathVariable("orderId") Long orderId) {
        //订单1
        List<LocalOrderVO> localOrderVOS = new ArrayList<>();
        LocalOrder localOrder=localOrdersService.selectByPK(orderId);
        LocalOrderVO localOrderVO=new LocalOrderVO();
        localOrderVO.setOrderId(localOrder.getOrderId());
        localOrderVO.setOrderSn(localOrder.getOrderSn());
        localOrderVO.setCompanyId(localOrder.getCompanyId());
        localOrderVO.setStrcompanyname(companyService.selectByPK(localOrder.getCompanyId()).getCompanyName());
        localOrderVO.setStrlinkman(companyService.selectByPK(localOrder.getCompanyId()).getLinkman());
        localOrderVO.setUserId(localOrder.getUserId());
        localOrderVO.setStrnickname(sysUserService.selectByPK(localOrder.getUserId()).getNickname());
        localOrderVO.setStrphone(sysUserService.selectByPK(localOrder.getUserId()).getPhone());
        localOrderVO.setPriceVO(localOrder.getPrice().doubleValue());
        localOrderVO.setStrtime(TimeUtils.getDatetime(TimeUtils.TimeFormat.LONG_DATE_PATTERN_LINE, localOrder.getCtime()));
        localOrderVOS.add(localOrderVO);
        //订单2
        List<UserProfitVO> userProfitVOS=new ArrayList<>();
        UserProfit userProfit=new UserProfit();
        userProfit.setOrderId(orderId);
        List<UserProfit> userProfitList =userProfitService.select(userProfit);
        for (UserProfit up1:userProfitList){
            UserProfitVO userProfitVO=new UserProfitVO();
            userProfitVO.setUserId(up1.getUserId());
            userProfitVO.setNickname(sysUserService.selectByPK(up1.getUserId()).getNickname());
            userProfitVO.setStrtime(TimeUtils.getDatetime(TimeUtils.TimeFormat.LONG_DATE_PATTERN_LINE, up1.getCtime()));
            userProfitVO.setMtime(up1.getMtime());
            userProfitVO.setRstatus(up1.getRstatus());
            userProfitVO.setAmount(up1.getAmount());
            userProfitVO.setOrderId(up1.getOrderId());
            if (up1.getOrderType()==3){
                userProfitVO.setUserProfitvo(up1.getUserProfit().doubleValue() * 100);
            }else {
                userProfitVO.setUserProfitvo(up1.getUserProfit().doubleValue());
            }
            userProfitVO.setConsumerId(up1.getConsumerId());
            switch (up1.getOrderType()){
                case 0:
                    userProfitVO.setStrordertrpe("商城供货商订单返利");
                    break;
                case 1:
                    userProfitVO.setStrordertrpe("地面店扫码订单返利");
                    break;
                case 2:
                    userProfitVO.setStrordertrpe("商城微商订单返利");
                    break;
                case 3:
                    userProfitVO.setStrordertrpe("地面店扫码订单返积分");
                    break;
                case 4:
                    userProfitVO.setStrordertrpe("商城微商订单返积分");
                    break;
                case 5:
                    userProfitVO.setStrordertrpe("点餐订单返积分");
                    break;
                case 6:
                    userProfitVO.setStrordertrpe("点餐订单返返利");
                    break;
            }
            userProfitVO.setProfitId(up1.getProfitId());
            userProfitVO.setOrderSn(up1.getOrderSn());
            if (ObjectUtils.isEmpty(companyService.selectByPK(up1.getUserId()))){
                userProfitVO.setStrcompanytype("普通用户");
            }else {
                switch (companyService.selectByPK(up1.getUserId()).getCompanyType()){
                    case 0:
                        userProfitVO.setStrcompanytype("直接邀约人");
                        break;
                    case 1:
                        userProfitVO.setStrcompanytype("普通用户");
                        break;
                    case 3:
                        userProfitVO.setStrcompanytype("城市合伙人");
                        break;
                    case 4:
                        userProfitVO.setStrcompanytype("梦想合伙人");
                        break;
                    case 8:
                        userProfitVO.setStrcompanytype("供货商");
                        break;
                    case 11:
                        userProfitVO.setStrcompanytype("互动商家(至尊版)");
                        break;
                    case 13:
                        userProfitVO.setStrcompanytype("互动商家(基础版)");
                        break;
                }
            }
            userProfitVOS.add(userProfitVO);
        }
        HttpServletResponse response = this.getResponse();
        //设置response头信息
        response.reset();
        response.setContentType("application/vnd.ms-excel");        //改成输出excel文件
        String fileName =localOrderVO.getStrnickname();
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");

        //创建工作簿并发送到浏览器
        try {
            //创键Excel表格中的第一个表,命名为"第一页"
            WritableWorkbook book = Workbook.createWorkbook(response.getOutputStream());
//第一sheet
            WritableSheet sheet = book.createSheet("订单详情", 0);
            //设置该单元格的表头
            List<String> keys = new ArrayList<>();
            keys.add("订单号");
            keys.add("订单编号");
            keys.add("公司ID");
            keys.add("公司名称");
            keys.add("公司负责人");
            keys.add("消费者ID");
            keys.add("消费者名字");
            keys.add("消费者电话");
            keys.add("消费金额");
            keys.add("订单时间");
            // 添加标题
            for (int x = 0; x < keys.size(); x++) {
                sheet.addCell((WritableCell) new Label(x, 0, keys.get(x)));
            }
            // 添加数据
            for (int y = 0; y < localOrderVOS.size(); y++) {
                sheet.addCell(new Label(0, y + 1, localOrderVOS.get(y).getOrderId().toString()));
                sheet.addCell(new Label(1, y + 1, localOrderVOS.get(y).getOrderSn()));
                sheet.addCell(new Label(2, y + 1, localOrderVOS.get(y).getCompanyId().toString()));
                sheet.addCell(new Label(3, y + 1, localOrderVOS.get(y).getStrcompanyname()));
                sheet.addCell(new Label(4, y + 1, localOrderVOS.get(y).getStrlinkman()));
                sheet.addCell(new Label(5, y + 1, localOrderVOS.get(y).getUserId().toString()));
                sheet.addCell(new Label(6, y + 1, localOrderVOS.get(y).getStrnickname()));
                sheet.addCell(new Label(7, y + 1, localOrderVOS.get(y).getStrphone()));
                sheet.addCell(new Label(8, y + 1, localOrderVOS.get(y).getPriceVO().toString()));
                sheet.addCell(new Label(9, y + 1, localOrderVOS.get(y).getStrtime()));
            }
//第二个sheet
            WritableSheet sheet2 = book.createSheet("返利详情", 1);

            //设置该单元格的表头
            List<String> keys2 = new ArrayList<>();
            keys2.add("订单号");
            keys2.add("订单编号");
            keys2.add("受益人ID");
            keys2.add("受益者名字");
            keys2.add("受益者类型");
            keys2.add("返利类型");
            keys2.add("返利金额");
            keys2.add("订单时间");
            // 添加标题
            for (int x = 0; x < keys2.size(); x++) {
                sheet2.addCell((WritableCell) new Label(x, 0, keys2.get(x)));
            }
            // 添加数据
            for (int y = 0; y < userProfitVOS.size(); y++) {
                sheet2.addCell(new Label(0, y + 1, userProfitVOS.get(y).getOrderId().toString()));
                sheet2.addCell(new Label(1, y + 1, userProfitVOS.get(y).getOrderSn()));
                sheet2.addCell(new Label(2, y + 1, userProfitVOS.get(y).getUserId().toString()));
                sheet2.addCell(new Label(3, y + 1, userProfitVOS.get(y).getNickname()));
                sheet2.addCell(new Label(4, y + 1, userProfitVOS.get(y).getStrcompanytype()));
                sheet2.addCell(new Label(5, y + 1, userProfitVOS.get(y).getStrordertrpe()));
                sheet2.addCell(new Label(6, y + 1, userProfitVOS.get(y).getUserProfitvo().toString()));
                sheet2.addCell(new Label(7, y + 1, userProfitVOS.get(y).getStrtime()));
            }

            // 写入数据并关闭文件
            book.write();
            book.close();
        } catch (Exception e) {

        }
    }

    /**
     * @api {get} /api/admin/localOrders/excel/list 后台管理-订单管理-商城订单-批量Excel导出
     * @apiSampleRequest /api/admin/localOrders/excel/list
     * @apiVersion 0.1.0
     * @apiName adminLocalOrderExcelList
     * @apiGroup LocalOrder
     *
     * @apiParam {string} stime 开始时间.
     * @apiParam {string} etime 结束时间.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     * @apiError Internal Server Error.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/localOrders/excel/list"
     *  }
     */


    @RequestMapping(value = {"/api/admin/localOrders/excel/list"})
    public void adminLocalOrderExcelList(LocalOrder localOrder) {
        //订单1
        localOrder.setPayStatus((byte)1);
        List<LocalOrderVO> localOrderVOS = new ArrayList<>();
        List<LocalOrder> localOrders=localOrdersService.select(localOrder);
        for (LocalOrder lo:localOrders){
            LocalOrderVO localOrderVO=new LocalOrderVO();
            localOrderVO.setOrderId(lo.getOrderId());
            localOrderVO.setOrderSn(lo.getOrderSn());
            localOrderVO.setCompanyId(lo.getCompanyId());
            localOrderVO.setStrcompanyname(companyService.selectByPK(lo.getCompanyId()).getCompanyName());
            localOrderVO.setStrlinkman(companyService.selectByPK(lo.getCompanyId()).getLinkman());
            localOrderVO.setUserId(lo.getUserId());
            localOrderVO.setStrnickname(sysUserService.selectByPK(lo.getUserId()).getNickname());
            localOrderVO.setStrphone(sysUserService.selectByPK(lo.getUserId()).getPhone());
            localOrderVO.setPriceVO(lo.getPrice().doubleValue());
            localOrderVO.setStrtime(TimeUtils.getDatetime(TimeUtils.TimeFormat.LONG_DATE_PATTERN_LINE, lo.getCtime()));
            localOrderVOS.add(localOrderVO);
        }
        //订单2
        List<UserProfitVO> userProfits=new ArrayList<>();
        UserProfit userProfit=new UserProfit();
        for (LocalOrder lo1:localOrders){
            userProfit.setOrderSn(lo1.getOrderSn());
            List<UserProfit> userProfitList =userProfitService.select(userProfit);
            for (UserProfit up1:userProfitList){
                UserProfitVO userProfitVO=new UserProfitVO();
                userProfitVO.setUserId(up1.getUserId());
                userProfitVO.setNickname(sysUserService.selectByPK(up1.getUserId()).getNickname());
                userProfitVO.setStrtime(TimeUtils.getDatetime(TimeUtils.TimeFormat.LONG_DATE_PATTERN_LINE, up1.getCtime()));
                userProfitVO.setMtime(up1.getMtime());
                userProfitVO.setRstatus(up1.getRstatus());
                userProfitVO.setAmount(up1.getAmount());
                userProfitVO.setOrderId(up1.getOrderId());
                if (up1.getOrderType()==3){
                    userProfitVO.setUserProfitvo(up1.getUserProfit().doubleValue() * 100);
                }else {
                    userProfitVO.setUserProfitvo(up1.getUserProfit().doubleValue());
                }
                userProfitVO.setConsumerId(up1.getConsumerId());
                switch (up1.getOrderType()){
                    case 0:
                        userProfitVO.setStrordertrpe("商城供货商订单返利");
                        break;
                    case 1:
                        userProfitVO.setStrordertrpe("地面店扫码订单返利");
                        break;
                    case 2:
                        userProfitVO.setStrordertrpe("商城微商订单返利");
                        break;
                    case 3:
                        userProfitVO.setStrordertrpe("地面店扫码订单返积分");
                        break;
                    case 4:
                        userProfitVO.setStrordertrpe("商城微商订单返积分");
                        break;
                    case 5:
                        userProfitVO.setStrordertrpe("点餐订单返积分");
                        break;
                    case 6:
                        userProfitVO.setStrordertrpe("点餐订单返返利");
                        break;
                }
                userProfitVO.setProfitId(up1.getProfitId());
                userProfitVO.setOrderSn(up1.getOrderSn());
                if (ObjectUtils.isEmpty(companyService.selectByPK(up1.getUserId()))){
                    userProfitVO.setStrcompanytype("普通用户");
                }else {
                    switch (companyService.selectByPK(up1.getUserId()).getCompanyType()){
                        case 0:
                            userProfitVO.setStrcompanytype("直接邀约人");
                            break;
                        case 1:
                            userProfitVO.setStrcompanytype("普通用户");
                            break;
                        case 3:
                            userProfitVO.setStrcompanytype("城市合伙人");
                            break;
                        case 4:
                            userProfitVO.setStrcompanytype("梦想合伙人");
                            break;
                        case 8:
                            userProfitVO.setStrcompanytype("普通用户");
                            break;
                        case 11:
                            userProfitVO.setStrcompanytype("互动商家(至尊版)");
                            break;
                        case 13:
                            userProfitVO.setStrcompanytype("互动商家(基础版)");
                            break;
                    }
                }
                userProfits.add(userProfitVO);
            }
        }

        HttpServletResponse response = this.getResponse();
        //设置response头信息
        response.reset();
        response.setContentType("application/vnd.ms-excel");        //改成输出excel文件
        String fileName ="LocalOrder";
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");

        //创建工作簿并发送到浏览器
        try {
            //创键Excel表格中的第一个表,命名为"第一页"
            WritableWorkbook book = Workbook.createWorkbook(response.getOutputStream());
//第一sheet
            WritableSheet sheet = book.createSheet("订单详情", 0);
            //设置该单元格的表头
            List<String> keys = new ArrayList<>();
            keys.add("订单号");
            keys.add("订单编号");
            keys.add("公司ID");
            keys.add("公司名称");
            keys.add("公司负责人");
            keys.add("消费者ID");
            keys.add("消费者名字");
            keys.add("消费者电话");
            keys.add("消费金额");
            keys.add("订单时间");
            // 添加标题
            for (int x = 0; x < keys.size(); x++) {
                sheet.addCell((WritableCell) new Label(x, 0, keys.get(x)));
            }
            // 添加数据
            for (int y = 0; y < localOrderVOS.size(); y++) {
                sheet.addCell(new Label(0, y + 1, localOrderVOS.get(y).getOrderId().toString()));
                sheet.addCell(new Label(1, y + 1, localOrderVOS.get(y).getOrderSn()));
                sheet.addCell(new Label(2, y + 1, localOrderVOS.get(y).getCompanyId().toString()));
                sheet.addCell(new Label(3, y + 1, localOrderVOS.get(y).getStrcompanyname()));
                sheet.addCell(new Label(4, y + 1, localOrderVOS.get(y).getStrlinkman()));
                sheet.addCell(new Label(5, y + 1, localOrderVOS.get(y).getUserId().toString()));
                sheet.addCell(new Label(6, y + 1, localOrderVOS.get(y).getStrnickname()));
                sheet.addCell(new Label(7, y + 1, localOrderVOS.get(y).getStrphone()));
                sheet.addCell(new Label(8, y + 1, localOrderVOS.get(y).getPriceVO().toString()));
                sheet.addCell(new Label(9, y + 1, localOrderVOS.get(y).getStrtime()));
            }
//第二个sheet
            WritableSheet sheet2 = book.createSheet("返利详情", 1);

            //设置该单元格的表头
            List<String> keys2 = new ArrayList<>();
            keys2.add("订单号");
            keys2.add("订单编号");
            keys2.add("受益人ID");
            keys2.add("受益者名字");
            keys2.add("受益者类型");
            keys2.add("返利类型");
            keys2.add("返利金额");
            keys2.add("订单时间");
            // 添加标题
            for (int x = 0; x < keys2.size(); x++) {
                sheet2.addCell((WritableCell) new Label(x, 0, keys2.get(x)));
            }
            // 添加数据
            for (int y = 0; y < userProfits.size(); y++) {
                sheet2.addCell(new Label(0, y + 1, userProfits.get(y).getOrderId().toString()));
                sheet2.addCell(new Label(1, y + 1, userProfits.get(y).getOrderSn()));
                sheet2.addCell(new Label(2, y + 1, userProfits.get(y).getUserId().toString()));
                sheet2.addCell(new Label(3, y + 1, userProfits.get(y).getNickname()));
                sheet2.addCell(new Label(4, y + 1, userProfits.get(y).getStrcompanytype()));
                sheet2.addCell(new Label(5, y + 1, userProfits.get(y).getStrordertrpe()));
                sheet2.addCell(new Label(6, y + 1, userProfits.get(y).getUserProfitvo().toString()));
                sheet2.addCell(new Label(7, y + 1, userProfits.get(y).getStrtime()));
            }

            // 写入数据并关闭文件
            book.write();
            book.close();
        } catch (Exception e) {

        }
    }
}
